package controllers;

import java.util.HashMap;
import java.util.Map;

import data.IPermitDAO;
import data.PermitDAO;
import models.Permit;
import spark.Request;
import spark.Response;

public class PermitController extends BaseController {
	private IPermitDAO dao;
	public PermitController(Request request, Response response) {
		super(request, response);
		dao = new PermitDAO();
	}
	
	public Object list() {
		Map<String, Object> attributes = new HashMap<>();
		try{
		
		attributes.put("permits", dao.list());
		}catch(Exception e) {
			attributes.put("error", e.fillInStackTrace().getMessage());
			e.printStackTrace();
			e.fillInStackTrace().getMessage();
			return render(attributes, "error.html");
		}
		return render(attributes, "permit/list.html");
	}
	
	public Object view(){
		int id = Integer.parseInt( request.params(":id"));
		Map<String, Object> attributes = new HashMap<>();
		attributes.put("permit", dao.get(id));
		return render(attributes, "permit/view.html");
	}
	
	public Object add() {
		if(request.requestMethod().toUpperCase().equals("GET")){
			Map<String, Object> attributes = new HashMap<>();
			attributes.put("permit", new Permit());
			attributes.put("tutors", dao.listStudentTutors(this.getCredentials().getPersonId()));
			return render(attributes, "permit/add.html");
		}else {
			String title = request.queryParams("title");
			String description = request.queryParams("description");
			int tutorId = Integer.parseInt(request.queryParams("tutorId"));
			dao.insert(title, description, tutorId, this.getCredentials().getPersonId());
			response.status(201);
			redirect("permits");
			return "";
		}
	}

}
